<?php
    class DbCache {
    private static $cacheTable = null;

    public function __construct() {
        self::$cacheTable = Table::getTable('cache', Config::get('CACHE_DBCONN'));
    }

    public static function set($nameSpace, $key, $val, $expire=0) {
        self::$cacheTable->delete($key);
        if($expire != 0)
            $expire = $expire > time() ? $expire : time() + $expire;
        self::$cacheTable->save(array('cache_key'=>$key,
                                      'cache_namespace'=>$nameSpace,
                                      'cache_value'=>serialize($val),
                                      'cache_expire'=>$expire));
    }

    public static function get($key) {
        $findCond = 'cache_key=' . quote($key) . ' AND (cache_expire =0 OR cache_expire >= ' . time() . ')';
        $cacheRecord = self::$cacheTable->find($findCond);
        if($cacheRecord) return unserialize($cacheRecord['cache_value']);
        return false;
    }

    public static function delete($key) {
        self::$cacheTable->delete($key);
    }

    public static function deleteNameSpace($nameSpace) {
        self::$cacheTable->delete(array('cache_namespace'=>$nameSpace));
    }

    public static function close() {
        self::$cacheTable->vacuum();
    }
};?>